import axios from 'axios';
import { history } from 'umi';

//拦截器

//第1步：创建实例

if (process.env.NODE_ENV === 'development') {
  //默认的是api
  axios.defaults.baseURL = '';
} else {
  // @ts-ignore
  //总的地址

  axios.defaults.baseURL = 'http://192.168.248.70:8084/';
}

const instance = axios.create({
  headers: {
    'x-requested-with': 'XMLHttpRequest',
  },
});

axios.defaults.headers.Authorization = sessionStorage.getItem('apiKey'); //默认头部

//第2步：添加请求拦截
//第3步：添加响应拦截
instance.interceptors.response.use(
  (response: any) => {
    // token
    let token = sessionStorage.getItem('apiKey');
    token && (response.headers.Authorization = token);

    if (!response.data.success && response.data.code === 'FAILURE') {
      return Promise.reject(response);
    } else if (
      !response.data.success &&
      response.data.code === 'UNAUTHORIZED'
    ) {
      history.replace('/401');

      //对响应错误做什么
      return Promise.reject(response);
    }
    return response.data;
  },
  (error: any) => {
    if (error.response) {
      if (error.response.status === 401) {
        history.replace('/401');
      } else if (error.response.status === 403) {
        history.replace('/403');
      } else {
        history.replace('/500');
      }
      return Promise.reject(error.response);
    }
    history.replace('/500');
    return Promise.reject(error);
  },
);

export default instance;
